from sqlalchemy import create_engine, Column, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime
from config.database_config import DATABASE_URL
from contextlib import contextmanager

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    user_id = Column(Integer, primary_key=True, index=True)
    username = Column(String, unique=True, index=True)
    role = Column(String, index=True)
    phone = Column(String, index=True)
    created_at = Column(DateTime, default=datetime.utcnow)

engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

@contextmanager
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

#查询所有记录
def get_users(db):
    return db.query(User).all()

#新增用户
def add_user(db, username, role, phone):
    new_user = User(username=username, role=role, phone=phone)
    db.add(new_user)
    db.commit()
    db.refresh(new_user)
    return new_user

#修改用户
def update_user(db, user_id, username=None, role=None, phone=None):
    user = db.query(User).filter(User.user_id == user_id).first()
    if not user:
        return None

    if username is not None:
        user.username = username
    if role is not None:
        user.role = role
    if phone is not None:
        user.phone = phone
    db.commit()
    db.refresh(user)
    return user

#删除用户
def delete_user(db, user_id):
    user = db.query(User).filter(User.user_id == user_id).first()
    if not user:
        return None

    db.delete(user)
    db.commit()
    return user